#include "Protocol.h"
#include "UserOS\OS_Event.h"
#include "Driver\USART.h"

U_Pack  RecvMsg;
Typedef_VerInfo DeviceInfo;
uint8 CntSendState=0;

void initProtocol(void)
{
    DeviceInfo.fw_ver1 = PROTOCOL_FW_VER1;
    DeviceInfo.fw_ver2 = PROTOCOL_FW_VER2;
    DeviceInfo.hw_ver1 = PROTOCOL_HW_VER1;
    DeviceInfo.hw_ver2 = PROTOCOL_HW_VER2;
    DeviceInfo.bd_type = PROTOCOL_BD_TYPE_HALL;
    DeviceInfo.bd_ver  = PROTOCOL_BD_VER;

    CntSendState = 0;
}

uint8 Protocol_CalcCheckSum(uint8* buf, uint8 size, uint8 initValue)
{
    uint8 cs = initValue;
    uint8 i;

    for(i=0; i<size; i++)
    {
        cs += buf[i];
    }

    return cs;
}

void Protocol_Send(uint8 cmd, uint8* para, uint8 size_para)
{
    U_Pack    sendMsg;
    memset(sendMsg.Buf,0,sizeof(U_Pack));
    sendMsg.Detail.Head        = PROTOCOL_HEAD;
    sendMsg.Detail.DeviceID    = PROTOCOL_DEVICE_ID;
    sendMsg.Detail.End         = PROTOCOL_END;
    sendMsg.Detail.Cmd         = cmd;
    memcpy(sendMsg.Detail.Para,para,size_para);
    sendMsg.Detail.CheckSum = Protocol_CalcCheckSum(sendMsg.Buf,sizeof(sendMsg)-1,0);
    USART_SendBuf(sendMsg.Buf,sizeof(U_Pack));
    CntSendState = 0;
}

void Protocol_RecvProc(void)
{
    if(OS_GetEvent(OS_EVENT_USART_RX_TIME_OUT))
    {
        OS_ClrEvent(OS_EVENT_USART_RX_TIME_OUT);
        if(USART_RxCnt == sizeof(Typedef_Pack))
        {
            memcpy(RecvMsg.Buf,USART_RxBuf,USART_RxCnt);

            if((RecvMsg.Detail.Head == PROTOCOL_HEAD)&&
               (RecvMsg.Detail.End == PROTOCOL_END) &&
               (RecvMsg.Detail.DeviceID == PROTOCOL_DEVICE_ID) &&
               (RecvMsg.Detail.CheckSum == Protocol_CalcCheckSum(RecvMsg.Buf,sizeof(Typedef_Pack)-2,0)))   
            {
                OS_SetEvent(OS_EVENT_PROTOCOL_RECV_OK);
            }

        }
    }
}

void Protocol_TimeServer(void)
{
    CntSendState++;
    if(CntSendState >= TM_SEND_STATE)      //*10ms
    {
        CntSendState = 0;
        OS_SetEvent(OS_EVENT_SEND_STATE);
    }
}

